import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    //初始化的数据
    list: [],
    //获取input框的值
    iptValue: "",
    nextId: 5,
    btnStatus: "all",
  },
  mutations: {
    //初始化数据
    showData(state, list) {
      state.list = list;
    },
    //input框的值
    setIptValue(state, val) {
      state.iptValue = val;
    },
    //添加列表项
    addItemTodolist(state) {
      const obj = {
        id: state.nextId,
        info: state.iptValue,
        done: false,
      };
      state.list.push(obj);
      state.nextId++;
      state.iptValue = "";
    },
    //删除列表项
    delItemTodoList(state, id) {
      const i = state.list.findIndex((v) => v.id === id);
      state.list.splice(i, 1);
    },
    //复选框状态更改
    changeCkStatus(state, params) {
      const index = state.list.findIndex((v) => v.id === params.id);
      if (index !== -1) {
        state.list[index].done = params.status;
      }
    },
    //根据按钮切换数据
    changeBtnStatus(state, key) {
      state.btnStatus = key;
    },
    //清除已完成
    clearDone(state){
      state.list = state.list.filter(v => v.done!==true)
    }
  },
  actions: {
    getList(context) {
      axios.get("/index.json").then((res) => {
        context.commit("showData", res.data);
      });
    },
  },
  getters: {
    unDoneLength(state) {
      return state.list.filter((v) => v.done !== true).length;
    },
    changeItemList(state) {
      if (state.btnStatus === "all") {
        return state.list;
      } 
      else if (state.btnStatus === "undone") {
        return state.list.filter((v) => v.done === false);
      } 
      else if (state.btnStatus === "done") {
        return state.list.filter((v) => v.done === true);
      } 
      else {
        return state.list;
      }
    },
  },
  modules: {},
});
